<?php

namespace App\Services;

use App\UploadedFile;
use Illuminate\Http\UploadedFile as LaravelUploadedFile;

class CommonService
{
    public function __construct()
    {
        $this->logSvc = new LogService;
    }

    public function storeUploadedFile(LaravelUploadedFile $file)
    {
        $dir = '/upload/' . date('Ymd') . '/' . $this->uuid();
        $dirRealPath = public_path($dir);
        if (!file_exists($dirRealPath)) {
            @mkdir($dirRealPath, 0777, true);
        }
        $originalFilename = $file->getClientOriginalName();
        $originalFilename = urldecode($originalFilename);
        $pathinfo = pathinfo($originalFilename);
        $extension = strtolower($pathinfo['extension']);
        $filename = $pathinfo['filename'];
        $filename = preg_replace('([\./\\\\~&])', '', $filename);
        $filename .= '.' . $extension;
        $path = "$dir/$filename";
        // 额外安全检查
        if (in_array($extension, ['zip', 'rar', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'jpg', 'jpeg', 'gif', 'png', 'tif', 'bmp'], true)) {
            $file->move($dirRealPath, $filename);
        }
        $record = new UploadedFile;
        $record->filename = $filename;
        $record->extension = $extension;
        $record->path = $path;
        $record->save();
        return $record;
    }

    public function uuid()
    {
        mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = substr($charid, 0, 8) . $hyphen
            . substr($charid, 8, 4) . $hyphen
            . substr($charid, 12, 4) . $hyphen
            . substr($charid, 16, 4) . $hyphen
            . substr($charid, 20, 12);
        return $uuid;
    }


    public function secondArrayUniqueByKey($arr, $key){
        $tmp_arr = array();
        foreach($arr as $k => $v)
        {
            if(in_array($v->{$key}, $tmp_arr))  //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            {
                unset($arr[$k]); //销毁一个变量 如果$tmp_arr中已存在相同的值就删除该值
            }else {
                $tmp_arr[$k] = $v->{$key}; //将不同的值放在该数组中保存
            }
        }
        //ksort($arr); //ksort函数对数组进行排序(保留原键值key) sort为不保留key值
        return $arr;
    }


}